package com.contatos.gui;

import com.contatos.control.ContatoControl;
import com.contatos.model.Contato;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Christian
 * Date: 29/04/14
 * Time: 21:12
 * To change this template use File | Settings | File Templates.
 */
public class TelaInicial extends JFrame{
    private JPanel telaInicial;
    private JToolBar mainToolbar;
    private JButton createButton;
    private JButton readButton;
    private JPanel cards;
    private JPanel createCard;
    private JTextField nomeInput;
    private JTextField enderecoInput;
    private JTextField emailInput;
    private JTextField telefoneInput;
    private JPanel emptyCard;
    private JButton cadastrarButton;
    private JPanel readCard;
    private JTable contatosTable;
    private JPanel updateCard;
    private JTextField nomeUpdate;
    private JTextField enderecoUpdate;
    private JTextField emailUpdate;
    private JTextField telefoneUpdate;
    private JButton updateButton;
    private JButton excludeBtn;
    private JPanel cardCreate;

    public TelaInicial(){
        super("TelaInicial");
        setLookAndFeel();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(telaInicial);
        pack();
        setTitle("AGENDA DE CONTATOS");
        setLocationRelativeTo(null);
        setVisible(true);

        createCardsLayout();


    }

    public void setLookAndFeel(){
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void createCardsLayout(){
        cards.add("EMPTY", emptyCard);
        cards.add("CREATE", createCard);
        cards.add("READ", readCard);
        cards.add("UPDATE", updateCard);

        createButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setupCreatePanel();
                CardLayout cardLayout = (CardLayout)(cards.getLayout());
                cardLayout.show(cards, "CREATE");
            }
        });

        readButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setupReadPanel();
                CardLayout cardLayout = (CardLayout)(cards.getLayout());
                cardLayout.show(cards, "READ");
            }
        });
    }

    public void setupCreatePanel(){
        cadastrarButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String nome = nomeInput.getText();
                String endereco = enderecoInput.getText();
                String email = emailInput.getText();
                String telefone = telefoneInput.getText();
                ContatoControl contatoControl = new ContatoControl();
                Contato contato = new Contato(nome, email, endereco, telefone);
                int result = contatoControl.writeContato(contato);
                if (result > 0 ){
                    JOptionPane.showMessageDialog(getParent(), "Contato Salvo com Sucesso!");
                    nomeInput.setText("");
                    enderecoInput.setText("");
                    emailInput.setText("");
                    telefoneInput.setText("");

                } else {
                    JOptionPane.showMessageDialog(getParent(), "Falha!");
                }

            }
        });
    }

    public void setupReadPanel(){
        DefaultTableModel tableModel = new DefaultTableModel(){
            public boolean isCellEditable(int row, int column){
                return false;
            }
        };
        tableModel.addColumn("Nome");
        tableModel.addColumn("Email");
        tableModel.addColumn("Endereço");
        tableModel.addColumn("Telefone");

        contatosTable.setModel(tableModel);
        ContatoControl contatoControl = new ContatoControl();
        ArrayList<Contato> contatos = contatoControl.readContato(null);
        for(Contato contato : contatos){
            tableModel.addRow(new Object[]{contato.getNome(),contato.getEmail(),contato.getEndereco(),contato.getTelefones()});
        }
        contatosTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Contato c = new Contato();
                if (e.getClickCount() == 2) {
                    JTable target = (JTable)e.getSource();
                    int row = target.getSelectedRow();
                    //int column = target.getSelectedColumn();
                    // do some action
                    CardLayout cardLayout = (CardLayout)(cards.getLayout());
                    cardLayout.show(cards, "UPDATE");
                    c = new Contato(target.getValueAt(row, 0).toString(),target.getValueAt(row, 1).toString(),target.getValueAt(row, 2).toString(),target.getValueAt(row, 3).toString());
                    c.setNome(target.getValueAt(row, 0).toString());
                    c.setEmail(target.getValueAt(row, 1).toString());
                    c.setEndereco(target.getValueAt(row, 2).toString());
                    c.setTelefones(target.getValueAt(row, 3).toString());
                }
                nomeUpdate.setText(c.getNome());
                enderecoUpdate.setText(c.getEndereco());
                emailUpdate.setText(c.getEmail());
                telefoneUpdate.setText(c.getTelefones());
                setupUpdatePanel(c);
            }
        });
    }

    public void setupUpdatePanel(Contato contato){
        final String chave = contato.getNome();
        updateButton.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Contato c = new Contato();
                        c.setNome(nomeUpdate.getText());
                        c.setEndereco(enderecoUpdate.getText());
                        c.setEmail(emailUpdate.getText());
                        c.setTelefones(telefoneUpdate.getText());
                        ContatoControl contatoControl = new ContatoControl();
                        int result = contatoControl.updateContato(c, chave);
                        if(result > 0){
                            JOptionPane.showMessageDialog(getParent(), "Contato Atualizado com Sucesso!");
                            CardLayout cardLayout = (CardLayout)(cards.getLayout());
                            setupReadPanel();
                            cardLayout.show(cards, "READ");
                        }
                    }
                }


        );
        excludeBtn.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Contato c = new Contato();
                        c.setNome(nomeUpdate.getText());
                        c.setEndereco(enderecoUpdate.getText());
                        c.setEmail(emailUpdate.getText());
                        c.setTelefones(telefoneUpdate.getText());
                        ContatoControl contatoControl = new ContatoControl();
                        int result = contatoControl.deleteContato(chave);
                        if(result > 0){
                            JOptionPane.showMessageDialog(getParent(), "Contato Excluido com Sucesso!");
                            CardLayout cardLayout = (CardLayout)(cards.getLayout());
                            setupReadPanel();
                            cardLayout.show(cards, "READ");
                        }
                    }
                }


        );

    }

}
